﻿/*
 * PsTFS is a set of PowerShell commands to manage and use Team Foundation Server. PowerShell 
 * effectiveness is combined with the power of TFS API to maximizes TFS capabilities.
 * 
 * Creator : Choulant Noham
 * Mail : choulant@gmail.com
 * Blog : http://choulant.blogspot.com
 * 
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;
using Microsoft.TeamFoundation.Client;
using Microsoft.TeamFoundation.VersionControl.Client;
using Microsoft.TeamFoundation.WorkItemTracking.Client;
using PsTFS.Objects;

namespace PsTFS.Commandes.Set
{
    /// <summary>
    /// Fusion entre deux branches
    /// </summary>
    [Cmdlet(VerbsCommon.Set, "Merge")]
    public class Set_Merge : PsCmdlet
    {          
        /// <summary>
        /// Permet de renvoyer les changesets du merge
        /// </summary>
        List<Changeset> listReturn = new List<Changeset>();

        /// <summary>
        /// Lancement du processus de fusion
        /// </summary>
        protected override void ProcessRecord()
        {
            Workspace workspace = null;

            // Get a reference to Version Control. 
            VersionControlServer versionControl = Methode_Service.VCS();

            // Create a workspace. 
            workspace = versionControl.CreateWorkspace(Guid.NewGuid().ToString(), versionControl.AuthenticatedUser);

            try
            {
                var _s = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @"\tempPsTFS\" + Guid.NewGuid().ToString() + @"\Source";
                var _t = Environment.GetFolderPath(Environment.SpecialFolder.InternetCache) + @"\tempPsTFS\" + Guid.NewGuid().ToString() + @"\Target";
                // Create a mapping using the Team Project supplied on the command line. 
                workspace.Map(Source, _s);
                workspace.Map(Target, _t);

                // Get the files from the repository. 
                workspace.Get();

                List<Changeset> listCS = new List<Changeset>();

                if (this.Workitem != null)
                {
                    listCS = (from WorkItem w in this.Workitem
                                  from Changeset cs in w.ListChangeset()
                                 select cs).Distinct().OrderBy(cs => cs.ChangesetId).ToList();
                }

                if (this.ChangeSet != null)
                {
                    listCS.AddRange(this.ChangeSet.OrderBy(cs => cs.ChangesetId).ToList());
                } 
                
                if(listCS.Count > 0)
                {
                    foreach (Changeset cs in listCS)
                    {
                        VersionSpec version = VersionSpec.ParseSingleSpec(cs.ChangesetId.ToString(), Context.Instance.TFS.AuthenticatedUserName);

                        Merge(workspace, version);
                    }
                }
                else
                {
                    Merge(workspace, null);
                }

            }
            catch (Exception ex)
            {
                ErrorRecord err = new ErrorRecord(ex, Error.GetInstance().GetError(this), ErrorCategory.WriteError, null);
                WriteError(err);
                Log.AddLog(null, ex.StackTrace);
            }
            finally
            {
                if (workspace != null)
                {
                    // Delete the workspace. 
                    bool delete = workspace.Delete();
                    base.ProcessRecord();
                }
            }

            WriteObject(listReturn);
        }

        private void Merge(Workspace workspace, VersionSpec version)
        {
            

            GetStatus status = workspace.Merge(Source,
            Target,
            version,
            version,
            LockLevel.None,
            RecursionType,
            MergeOptions);

            Console.WriteLine("Number conflicts : " + status.NumConflicts.ToString());
            Console.WriteLine("Number failures : " + status.NumFailures.ToString());
            Console.WriteLine("Number operations : " + status.NumOperations.ToString());
            Console.WriteLine("Number warnings : " + status.NumWarnings.ToString());

            Log.AddLog("Number conflicts : " + status.NumConflicts.ToString());
            Log.AddLog("Number failures : " + status.NumFailures.ToString());
            Log.AddLog("Number operations : " + status.NumOperations.ToString());
            Log.AddLog("Number warnings : " + status.NumWarnings.ToString());

            WriteObject(status.GetFailures(), true);

            Pending(workspace);
        }

        private void Pending(Workspace workspace)
        {

            Conflict[] conflicts = workspace.QueryConflicts(new string[] { Target }, true);

            foreach (Conflict conflict in conflicts)
            {
                if (workspace.MergeContent(conflict, true))
                {
                    conflict.Resolution = Resolution.AcceptMerge;
                    workspace.ResolveConflict(conflict);
                }
                if (conflict.IsResolved)
                {
                    workspace.PendEdit(conflict.TargetLocalItem);
                }
            }


            // Show our pending changes. 
            PendingChange[] pendingChanges = workspace.GetPendingChanges();

            Log.AddLog(null, "Your current pending changes:");

            if (pendingChanges.Length > 0)
            {
                foreach (PendingChange pendingChange in pendingChanges)
                {
                    Log.AddLog(null, "  path: " + pendingChange.LocalItem +
                                      ", change: " + PendingChange.GetLocalizedStringForChangeType(pendingChange.ChangeType));
                }

                // Checkin the items we added. 
                int changesetNumber = workspace.CheckIn(pendingChanges, Description);

                Log.AddLog(null, "Checked in changeset " + changesetNumber);

                listReturn.Add(workspace.VersionControlServer.GetChangeset(changesetNumber));
            }
            else
            {
                Log.AddLog(null, "Not changeset");

            }
        }
        /// <summary>
        /// Permet de récupérer la fin de la commande
        /// </summary>
        protected override void EndProcessing()
        {
            Log.AddLog(null, "Set-Merge is end");
            base.EndProcessing();
        }

        /// <summary>
        /// Object contenant Team Foundation Server 2008
        /// </summary>
        [Parameter(Position = 0)]
        public TfsTeamProjectCollection TFS
        {
            set { Context.Instance.TFS = value; }
        }

        /// <summary>
        /// Source de la fusion
        /// </summary>
        [Parameter(Position = 2, Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public string Source { get; set; }

        /// <summary>
        /// Destination de la fusion
        /// </summary>
        [Parameter(Position = 3, Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public string Target { get; set; }

        /// <summary>
        /// Description pour le changeset
        /// </summary>
        [Parameter(Position = 4, Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public string Description { get; set; }

        /// <summary>
        /// Type de récurtion (Full, None; OnLevel
        /// </summary>
        [Parameter(Position = 5, Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public RecursionType RecursionType { get; set; }

        /// <summary>
        /// Option de fusion
        /// </summary>
        [Parameter(Position = 6, Mandatory = true)]
        [ValidateNotNullOrEmpty]
        public MergeOptions MergeOptions { get; set; }

        /// <summary>
        /// Liste des workitem à fusionner
        /// </summary>
        [Parameter(Position = 7)]
        [ValidateNotNullOrEmpty]
        public List<WorkItem> Workitem { get; set; }

        /// <summary>
        /// Liste des changeset à fusionner
        /// </summary>
        [Parameter(Position = 8)]
        [ValidateNotNullOrEmpty]
        public List<Changeset> ChangeSet { get; set; }
    }
}
